import { ReactNode } from "react";
import { Input, Textarea, View } from "@tarojs/components";

export type FormInputProps = {
  type?: "text" | "digit" | "textarea" | "number";
  value?: string;
  disabled?: boolean;
  placeholder?: string;

  size?: "sm";
  rows?: number;
  round?: boolean;
  maxlength?: number;
  showLimitWords?: boolean;

  prefix?: ReactNode;
  suffix?: ReactNode;

  className?: string;
  onChange?: (e: string) => void;
  onClick?: (event: any) => void;
};

export default ({
  type,
  size,
  round,
  value,
  rows = 5,
  disabled,
  placeholder,
  maxlength,
  showLimitWords,
  className,

  prefix,
  suffix,

  onChange,
  onClick,
}: FormInputProps) => {
  const isTextarea = type === "textarea";

  return (
    <View
      className={`flex w-full shadow-inner-1 ${
        round ? "rounded-full" : "rounded-lg"
      } ${isTextarea ? "flex-col" : "items-center"} ${className}`}
      onClick={onClick}
    >
      {prefix && <View className="ml-3">{prefix}</View>}

      {type === "textarea" ? (
        <View className="flex-auto">
          <Textarea
            value={value}
            disabled={disabled}
            maxlength={maxlength}
            placeholder={placeholder}
            className={`w-full px-3 pt-3 h-[3em] ${showLimitWords && "pb-1"}`}
            onInput={(e) => onChange?.(e.detail.value)}
            style={{ height: rows + `em` }}
          />
        </View>
      ) : (
        <Input
          type={type}
          value={value}
          disabled={disabled}
          maxlength={maxlength}
          placeholder={placeholder}
          className={`w-full px-3 ${size == "sm" ? "h-[64px]" : "h-[82px]"}`}
          onInput={(e) => onChange?.(e.detail.value)}
        />
      )}

      {showLimitWords && (
        <View
          className={`text-right text-second mx-2 text-sm ${
            isTextarea && "mt-1 mb-2"
          }`}
        >
          {value?.length || 0}/{maxlength}
        </View>
      )}

      {suffix && <View className="mr-3">{suffix}</View>}
    </View>
  );
};
